<template>
  <div>
    <el-header>
      <van-nav-bar title="咖啡师" right-text="退出登录" @click-right="logout" />
    </el-header>
    <el-container style="height: max-content">
      <el-aside width="auto" style="height: 100%; background-color: white">
        <div style="font-weight: bold; font-size: large">
          {{ "欢迎进入咖啡师考试系统!" }}<br />
          {{ "请选择考试批次。" }}<br />
        </div>
        <el-button
          class="refresh-btn"
          @click="onRefresh"
          type="primary"
          circle
          icon="el-icon-refresh"
          size="large"
        />
      </el-aside>
      <el-container>
        <el-main>
          <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list
              v-model="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
            >
              <van-cell
                style="font-weight: bold; font-size: large; border: #8492a6 1px"
                center
                v-for="item in list"
                :key="item.id"
                :title="item.levelByTimeGroup + ': 【' + item.startTime + '】'"
                data-id="item"
                @click="toExam"
              />
            </van-list>
          </van-pull-refresh>
        </el-main>
      </el-container>
    </el-container>
    <!-- <div class="flc">
      <div class="video-Box">
        <div>
          <video
            id="videoCamera"
            width="250"
            height="250"
            autoplay
            style="border-radius: 180px; box-shadow: darkgrey 0 0 30px 5px"
          ></video>
        </div>
        <canvas
          style="display: none"
          id="canvasCamera"
          width="250"
          height="250"
        ></canvas>
      </div>
      <div class="img_bg_camera" v-if="imgSrc">
        <p style="color: #000000">图片显示</p>
        <img
          :src="imgSrc"
          alt=""
          class="tx_img"
          style="border-radius: 360px; box-shadow: darkgrey 0 0 30px 5px"
          v-if="imgif"
        />
      </div>
      <div class="bommen" style="margin-top: 50px">
        <el-button type="success" @click="getCompetence()"
          >打开摄像头</el-button
        >
        <el-button type="success" @click="closeCarama()">关闭摄像头</el-button>
        <el-button type="success" @click="setImage()">拍照</el-button>
        <el-button type="primary" @click="uploadImage()">提交</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </div> -->
  </div>
</template>

<script>
import { Message } from "element-ui";

import { listTime } from "@/api/examiner/examiner.js";
export default {
  name: "Examiner",
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      refreshing: false,

      imgif: false,
      videoWidth: 1920,
      videoHeight: 1080,
      imgSrc: "", //图片src
      canvasCamera: null,
      contextCamera: null,
      videoCamera: null,
    };
  },
  watch: {},
  created() {
    this.enterFullscreen();
  },
  methods: {
    // 打开摄像头
    getCompetence() {
      this.canvasCamera = document.getElementById("canvasCamera");
      this.contextCamera = this.canvasCamera.getContext("2d");
      this.videoCamera = document.getElementById("videoCamera");
      var _this = this;
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 新的浏览器使用srcObject。旧的浏览器可能没有srcObject
          if ("srcObject" in _this.videoCamera) {
            _this.videoCamera.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.videoCamera.src = window.URL.createObjectURL(stream);
          }
          _this.videoCamera.onloadedmetadata = function (e) {
            _this.videoCamera.play();
          };
        })
        .catch((err) => {
          console.log(err);
          Message({
            message: "没有开启摄像头权限或浏览器版本不兼容",
            type: "warning",
          });
        });
    },
    closeCarama() {
      this.videoCamera.srcObject.getTracks()[0].stop();
    },
    //  绘制图片（拍照功能）
    setImage() {
      this.imgif = true;
      // 点击，canvas画图
      this.contextCamera.drawImage(this.videoCamera, 0, 0, 250, 250);
      // 获取图片base64链接
      var image = this.canvasCamera.toDataURL("image/png");
      this.imgSrc = image;
      console.log(this.imgSrc);
    },
    save() {
      if (this.imgSrc) return this.$emit("creamOver", this.imgSrc);
      Message({ message: "还未进行拍摄", type: "error" });
    },
    //上传数据
    uploadImage() {
      var file = this.imgSrc;
      console.log(file);
      //base64数据放formData里面
      var formData = new FormData(); //*
      formData.append("multipartFile", file); //*
      formData.append("password", this.ruleForm.password); //*
      formData.append("username", this.ruleForm.name); //*
      //自己配置axios。上传
    },

    onLoad() {
      setTimeout(() => {
        if (this.refreshing) {
          this.list = [];
          this.refreshing = false;
        }

        // for (let i = 0; i < 10; i++) {
        //   this.list.push(this.list.length + 1);
        // }
        this.getTimeList();

        this.loading = false;
        this.finished = true;

        if (this.list.length >= 40) {
          this.finished = true;
        }
      }, 1000);
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    },
    async logout() {
      this.$confirm("确定注销并退出系统吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("LogOut").then(() => {
            location.href = "/index";
          });
        })
        .catch(() => {});
    },
    getTimeList() {
      // console.log("*$$$$$$$$$$$$$$$$$$$$$$")
      this.loading = false;
      listTime()
        .then((response) => {
          // console.log("*********",response)
          this.list = response.data;
          this.total = response.total;
          this.loading = false;
        })
        .catch((res) => {
          console.log("****ERROR*****", res);
        });
    },
    toExam(e) {
      const regex = /【(.*?)】/g;
      const match = e.srcElement.textContent.match(regex);
      const res = match.map((match) => match.slice(1, -1));
      console.log("params:", res[0]);
      this.$router.push({
        path: "/examiner/stuList",
        query: {
          batchTime: res[0],
        },
      });
    },
    enterFullscreen() {
      const element = document.documentElement; // 获取整个文档的根元素

      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.mozRequestFullScreen) {
        // Firefox
        element.mozRequestFullScreen();
      } else if (element.webkitRequestFullscreen) {
        // Chrome, Safari and Opera
        element.webkitRequestFullscreen();
      } else if (element.msRequestFullscreen) {
        // IE/Edge
        element.msRequestFullscreen();
      }
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.refresh-btn {
  position: fixed;
  bottom: 90px;
  /* 样式可根据需求自定义 */
}
.footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.flc {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.face {
  width: 400px;
  height: 450px;
  position: relative;
}

.face .face-img {
  width: 400px;
  height: 450px;
  position: absolute;
  left: 0px;
  top: 0px;
}

.face .face-content {
  width: 310px;
  height: 322px;
  position: absolute;
  top: 64px;
  left: 45px;
}

.face .face-content #video {
  object-fit: fill;
}

.step {
  text-align: center;
  margin-top: 30px;
}

.step .step-ul .step-li .step-title {
  font-size: 16px;
  color: #65dffe;
  padding-bottom: 10px;
}

.step .step-ul .step-li .step-title .step-titleimg {
  height: 26px;
  width: 26px;
  margin-left: 20px;
  cursor: pointer;
}

.step .step-ul .step-li .step-img {
  height: 150px;
  width: 150px;
  border: 3px solid #eecfa1;
  border-radius: 50%;
}

.step .step-ul .step-li .step-img img {
  height: 100%;
  width: auto;
}
</style>
